<template>
  <form @submit="userAddressSave">
    <cu-custom :bgColor="'bg-' + theme.backgroundColor" :isBack="true">
      <block slot="backText">返回</block>
      <block slot="content"
        >{{ userAddress.id ? "编辑" : "新增" }}收货地址</block
      >
    </cu-custom>
    <view class="address">
      <view class="cu-form-group">
        <view class="title">姓名</view>
        <input
          class="text-right"
          placeholder="请输入姓名"
          maxlength="10"
          name="userName"
          :value="userAddress.userName"
        />
      </view>
      <view class="cu-form-group">
        <view class="title">联系电话</view>
        <input
          class="text-right"
          placeholder="请输入电话"
          maxlength="20"
          name="telNum"
          :value="userAddress.telNum"
        />
      </view>
      <view class="cu-form-group">
        <view class="title">地址选择</view>
        <!-- #ifndef H5 || APP-PLUS || MP-ALIPAY -->
        <picker mode="region" @change="regionChange" :value="region">
          <view class="picker"
            >{{ region[0] }}，{{ region[1] }}，{{ region[2] }}</view
          >
        </picker>
        <!-- #endif -->
        <!-- #ifdef H5 || APP-PLUS || MP-ALIPAY -->
        <region-picker @change="regionChange" :value="region">
          <view class="picker"
            >{{ region[0] }}，{{ region[1] }}，{{ region[2] }}</view
          >
        </region-picker>
        <!-- #endif -->
      </view>
      <view class="cu-form-group">
        <view class="title">详细地址</view>
        <input
          class="text-right"
          placeholder="请输入详细地址"
          maxlength="50"
          name="detailInfo"
          :value="userAddress.detailInfo"
        />
      </view>
      <view class="cu-form-group">
        <view class="title">设为默认地址</view>
        <switch
          :checked="userAddress.isDefault == '1'"
          @change="isDefaultChange"
        ></switch>
      </view>

      <view class="compile">
        <!-- #ifdef MP-WEIXIN -->
        <button
          class="cu-btn shadow-blur block line-gray text-black round bottom-btn"
          @tap="getWxAddress"
          open-type="getUserInfo"
        >
          <text>导入微信地址</text>
        </button>
        <!-- #endif -->
        <button
          class="ml34 cu-btn shadow-blur block round bottom-btn"
          :class="'bg-' + theme.themeColor"
          formType="submit"
        >
          立即保存
        </button>
      </view>
    </view>
    <view class="del" @tap="userAddressDelete" v-if="userAddress.id">
      删除此地址
    </view>
  </form>
</template>

<script>
const app = getApp();
const util = require("utils/util.js");
import api from "utils/api";
import validate from "utils/validate";

import regionPicker from "@/components/region-picker/region-picker.vue";

export default {
  data() {
    return {
      CustomBar: this.CustomBar,
      theme: app.globalData.theme, //全局颜色变量
      region: ["选择省", "选择市", "选择区"],
      userAddress: {
        isDefault: "0",
        userAddress: "",
        telNum: "",
        detailInfo: "",
      },
    };
  },

  components: {
    regionPicker,
  },
  props: {},

  onLoad(options) {
    // 保存别人分享来的 userCode
    util.saveSharerUserCode(options);
    // 本地获取参数信息
    let that = this;
    uni.getStorage({
      key: "param-userAddressForm",
      success: function (res) {
        let userAddress = res.data;
        that.region[0] = userAddress.provinceName
          ? userAddress.provinceName
          : "选择省";
        that.region[1] = userAddress.cityName ? userAddress.cityName : "选择市";
        that.region[2] = userAddress.countyName
          ? userAddress.countyName
          : "选择区";
        if (userAddress.userName) {
          userAddress.isDefault = userAddress.isDefault
            ? userAddress.isDefault
            : "0";
          that.userAddress = userAddress;
        }
      },
    });
  },

  methods: {
    regionChange(e) {
      this.region = e.detail.value;
    },

    isDefaultChange(e) {
      if (e.detail.value) {
        this.userAddress.isDefault = "1";
      } else {
        this.userAddress.isDefault = "0";
      }
    },

    userAddressSave(e) {
      let value = e.detail.value;
      let region = this.region;

      if (!value.userName) {
        uni.showToast({
          title: "请填写收货人姓名",
          icon: "none",
          duration: 3000,
        });
        return;
      }

      if (!value.telNum) {
        uni.showToast({
          title: "请填写联系电话",
          icon: "none",
          duration: 3000,
        });
        return;
      }

      if (!validate.validateMobile(value.telNum)) {
        uni.showToast({
          title: "请输入正确的手机号码",
          icon: "none",
          duration: 3000,
        });
        return;
      }

      if (region[0] == "选择省") {
        uni.showToast({
          title: "请选择所在地区",
          icon: "none",
          duration: 3000,
        });
        return;
      }

      if (!value.detailInfo) {
        uni.showToast({
          title: "请填写详细地址",
          icon: "none",
          duration: 3000,
        });
        return;
      }

      api
        .userAddressSave({
          id: this.userAddress.id,
          userName: value.userName,
          telNum: value.telNum,
          provinceName: region[0],
          cityName: region[1],
          countyName: region[2],
          detailInfo: value.detailInfo,
          isDefault: this.userAddress.isDefault,
        })
        .then((res) => {
          uni.showToast({
            title: "操作成功",
            icon: "success",
            mask: true,
          });
          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
            });
          }, 1000);
        });
    },

    userAddressDelete() {
      let that = this;
      uni.showModal({
        content: "确认将这个地址删除吗？",
        cancelText: "我再想想",
        confirmColor: "#ff0000",
        success(res) {
          if (res.confirm) {
            api.userAddressDel(that.userAddress.id).then((res) => {
              uni.showToast({
                title: "删除成功",
                icon: "success",
                mask: true,
              });
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1,
                });
              }, 1000);
            });
          }
        },
      });
    },

    /*
     * 导入微信地址
     */
    getWxAddress: function () {
      let that = this;
      uni.authorize({
        scope: "scope.address",
        success: function (res) {
          uni.chooseAddress({
            success: function (res) {
              console.log(res, "成功");
              that.region[0] = res.provinceName;
              that.region[1] = res.cityName;
              that.region[2] = res.countyName;
              that.userAddress.userName = res.userName;
              that.userAddress.telNum = res.telNumber;
              that.userAddress.detailInfo = res.detailInfo;
            },
            fail: function (res) {
              console.log(res, "失败接口");
              if (res.errMsg == "chooseAddress:cancel") {
                uni.showToast({
                  title: "取消选择",
                  icon: "none",
                  duration: 3000,
                });
              }
            },
          });
        },
        fail: function (res) {
          console.log("-----fail");
          console.log(res);
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.address {
  margin: 32rpx;
  border-radius: 16rpx;
  overflow: hidden;
}
.bottom-btn {
  width: 100%;
  height: 88rpx;
  margin-bottom: 20rpx;
}

.compile {
  position: fixed;
  position: absolute;
  bottom: 0;
  left: 32rpx;
  right: 32rpx;
  display: flex;
  align-items: center;
  padding-bottom: 32rpx;
}
.del {
  font-size: 28rpx;
  color: #f55f4e;
  margin-top: 32rpx;
  margin-left: 64rpx;
}
</style>
